<?php
/**
 * User: yyxi@vip.deyi.com
 * Time: 11:57
 */

namespace Apps\Acp\Services;

use Apps\Acp\Models\AwardLog;
use Apps\Acp\Models\User;
use Apps\Common\Constant\CacheKeyConstant;
use Apps\Common\Constant\CacheTimeoutConstant;
use Apps\Weixin\Services\WxConfigService;
use Deyi\Functions\CacheFunction;
use Deyi\Functions\ObjectFunction;

class UserService extends User
{
    const REFRESH_FREQ = 3;

    public function getOneByFieldCache($field, $value, $refresh = false)
    {
        $cacheKey = CacheFunction::generateKey(CacheKeyConstant::FANLI_USER_CACHE_KEY, $field, $value);

        if ($refresh) {
            static::$_memcached->delete($cacheKey);
        }
        $res = static::$_memcached->get($cacheKey);

        if (is_array($res)) {
            return $res;
        }

        $res = $this->getOneByField($field, $value);
        if ($res) {
            $res = ObjectFunction::toAo($res);
            static::$_memcached->set($cacheKey, $res, CacheTimeoutConstant::LOCAL_SMALL_CACHE);
        }

        return $res;
    }

    public function cleanUserCache($field, $value)
    {
        $cacheKey = CacheFunction::generateKey(CacheKeyConstant::FANLI_USER_CACHE_KEY, $field, $value);

        static::$_memcached->delete($cacheKey);
    }

    public function refreshViews($id, $uid)
    {
        $cacheKey = CacheFunction::generateKey(CacheKeyConstant::FANLI_CAMPAIGN_VIEWS_CACHE_KEY, $id, $uid);
        if (static::$_redis->get($cacheKey)) {
            //return false;
        }
        $views = (int)static::$_redis->incr($cacheKey);

        if ($views >= mt_rand(1, self::REFRESH_FREQ)) {
            static::$_redis->watch($cacheKey);
            static::$_redis->multi()->del($cacheKey);
            if (static::$_redis->exec()) {
                $this->updateCount('views', $uid, $views);
            }
        }

        if ($views === 1) {
            static::$_redis->expire($cacheKey, CacheTimeoutConstant::LOCAL_DAY_CACHE);
        }

        if (!$views) {
            static::$_redis->del($cacheKey);
        }

        return true;
    }

    public function checkViews($uid, $id = 1)
    {
        if ($this->refreshViews($id, $uid)) {
            $cacheKey = CacheFunction::generateKey(CacheKeyConstant::FANLI_CAMPAIGN_VIEWS_CACHE_KEY, $id, $uid);

            $addViews = static::$_redis->get($cacheKey);

            $oldViews = $this->getViews($uid);


            $views_price = WxConfigService::getInstance()->getViewPrice();

            $views = $addViews + $oldViews;
            if (in_array($views, array_keys($views_price))) {
                User::getInstance()->updateCount('award', $uid, $views_price[$views]);
                AwardLog::getInstance()->insertByFields(['uid' => $uid, 'type' => 1, 'num' => $views_price[$views], 'dateline' => time()]);
            }
        }
    }
}